<template>
  <container-item-wrapper :widget="widget">
    <vxe-toolbar>
      <template v-if="!isReadMode" #buttons>
        <el-button v-if="widget.options.add" type="primary" @click="insertEvent()">{{ i18nt('designer.setting.operateAdd') }}</el-button>
        <el-button v-if="widget.options.delete" @click="removeSelectRows()">{{ i18nt('designer.setting.operateDelete') }}</el-button>
        <el-button v-if="widget.options.import" @click="importData()">{{ i18nt('designer.setting.operateImport') }}</el-button>
        <el-button v-if="widget.options.export" @click="exportData()">{{ i18nt('designer.setting.operateExport') }}</el-button>
        <el-button v-if="widget.options.refresh" @click="refresh()">{{ i18nt('designer.setting.operateRefresh') }}</el-button>
        <el-button v-if="this.widget.options.name === 'datatable67262' && showCost" @click="obtainCostInformation('硬件')">获取成本信息</el-button>
        <el-button v-if="this.widget.options.name === 'datatable70276' && showCost" @click="obtainCostInformation('硬件')">获取成本信息</el-button>
         <el-button v-if="this.widget.options.name === 'datatable37383'&& showCost" @click="obtainCostInformation('结构')">获取成本信息</el-button>
      </template>
    </vxe-toolbar>
    <vxe-grid
      ref="xGrid"
      v-bind="gridOptions"
      :columns="columns"
      row-class-name="data-table-widget-row"
      class="data-table-item"
      :stripe="widget.options.stripe"
      :height="tableHeight"
      :footer-method="footerMethod"
      :style="{ width: this.widget.options.tableWidth || '100%' }"
      :show-footer="widget.options.showSummary"
    >
      <template #pager v-if="widget.options.showPagination">
        <vxe-pager
          :layouts="
            widget.options.smallPagination ? ['PrevPage', 'Number', 'NextPage'] : ['Total', 'PrevPage', 'Number', 'PageCount', 'NextPage', 'Sizes', 'FullJump']
          "
          :current-page="currentPage"
          :page-size="pageSize"
          :pageSizes="[5, 10, 20, 50, 100]"
          :total="gridOptions.data.length"
          :align="widget.options.paginationAlign"
          @page-change="handleCurrentPageChange"
        ></vxe-pager>
      </template>
    </vxe-grid>
    <select-object-dialog v-model="showDialog" :field="widget" @confirm="confirmFunc" />
  </container-item-wrapper>
</template>

<script lang="jsx">
import formDesigner from '@common/form-designer';
import { request } from '@common/core';
import tyUi from '@common/ty-ui';

const { TyPlmInput } = tyUi.getExportResource( 'src/ty-ui/lib/ty-input/index.js');
const { TyPlmTimeDate } = tyUi.getExportResource( 'src/ty-ui/lib/ty-time-date/index.js');
const { TyPlmSelect } = tyUi.getExportResource( 'src/ty-ui/lib/ty-select/index.js');
const FormItemWrapper = formDesigner.getExportResource('src/form-designer/extension/form-render/data-table-item.vue');
export default {
  extends: FormItemWrapper.default,
  data() {
    return {
      showDialog: false,
      selectAllFlag: false,
      currentPage: 1,
      pageSize: 10,
      columns: [],
      showCost:false
    };
  },

  watch: {
    // modify by nieyz 2024/10/22 业务规则设置表格只读时重置表单列形态
    'widget.options.readonly': {
      handler(val) {
        this.makeColumns();
      }
    }
  },

  mounted() {
    this.isShowCost()
    console.log('组件替换成功');
    this.$nextTick(() => {
      this.handleOnMounted();
    });
  },
  methods: {
  async  isShowCost(){
    try {
       const res = await request({
        method: 'post',
    url: 'rest/v1/formFunction/verifyUserPermissions', 
    headers: {
          authorization: sessionStorage.getItem('authorization')
        },
        data: sessionStorage.getItem('userID')
      });
      if (res.success) {
       
      }else{
        this.showCost=true
      }
    } catch (error) {
    return false;
    }
      
  
    },
   async makeColumns() {
   let showC= this.isShowCost()
      const {
        showIndex,
        tableColumns,
        showCheckBox,
        operationButtons,
        buttonsColumnTitle,
        buttonsColumnWidth,
        buttonsColumnFixed,
        showButtonsColumn,
        readonly
      } = this.widget.options;
      const arr = [];
      // 获取所有下拉组件的枚举值选项
      const enumObj = await this.getSelectOptions();
      const widgetObj = { input: TyPlmInput, date: TyPlmTimeDate, select: TyPlmSelect };
      if (showCheckBox && !this.isReadMode) arr.push({ type: 'checkbox', width: 50, fixed: 'left' });
      if (showIndex) arr.push({ type: 'seq', width: 50, fixed: 'left' });
      tableColumns.forEach(({ field, title, width, fixed, align, formatter, sortable, show, render, edit, component, enum: emumData }) => {
        const column = { field, title, width, fixed, align, sortable, visible: show };
        // modify by nieyz 2024/10/22 业务规则设置表格只读时列禁止编辑
        if (!this.isReadMode && edit && component) {
          column.editRender = {};
          const render = ({ row, column }) => {
            const props = {
              modelValue: row[field],
              ['onUpdate:modelValue']: (value) => {
                row[field] = component === 'date' ? moment(value).format(formatter || 'YYYY-MM-DD') : value;
              }
            };
            // 下拉组件传下拉选项参数
            if (component === 'select') {
              props.options = { list: emumData?.enumOid ? enumObj[emumData.enumOid] : emumData?.list };
            }
            if (formatter) {
              props.format = formatter;
            }
            return h(widgetObj[component], props);
          };
          column.slots = {
            // 获取显示值，默认显示只读态
            default: ({ row, column }) => this.getDisplayText(component, row, column, emumData, enumObj),
            edit: render
          };
        } else if (render) {
          column.editRender = {};
          column.slots = {
            default: ({ row, column }) => row[field],
            edit: ({ row, column }) => {
              const func = new Function('h', 'params', 'components', render);
              const components = this.$root.$.appContext.components;
              return func(
                h,
                {
                  modelValue: row[field],
                  readonly,
                  ['onUpdate:modelValue']: (value) => {
                    row[field] = value;
                  }
                },
                components
              );
            }
          };
        }
         
         if (showC && field=='cost') {
          arr.push(column)
         }
        if (show && field!=='cost') arr.push(column);
      });
      if (showButtonsColumn && operationButtons.length && operationButtons.some((item) => !item.hidden)) {
        const column = { field: 'operate', title: buttonsColumnTitle, width: buttonsColumnWidth, fixed: buttonsColumnFixed };
        column.slots = {
          default: ({ row, rowIndex }) => {
            const obj = {};
            operationButtons
              .filter((item) => !item.hidden)
              .forEach(
                ({ name, label, ...rest }) =>
                  (obj[name] = () => (
                    <el-button link {...rest} onClick={() => this.operateButtonsClick(name, rowIndex, row)}>
                      {' '}
                      {label}
                    </el-button>
                  ))
              );
            return <OperateBUttonsWrap>{obj}</OperateBUttonsWrap>;
          }
        };
  
          arr.push(column);
      
        
      }
      this.columns = arr;

      
    },
    handleOnCreated() {
      if (!!this.widget.options.onCreated) {
        let customFunc = new Function(this.widget.options.onCreated);
        customFunc.call(this);
      }
    },
async obtainCostInformation(param){
 const $table = this.$refs.xGrid;


const numArray = this.$refs.xGrid.getTableData()?.tableData?.map(item => item.num);
let costData=[]
  if (param==='硬件') {
     const res = await request({
        method: 'post',
    url: ' /rest/v1/formFunction/obtainCostInformation?user='+sessionStorage.getItem('userID')+'&form=硬件', 
    headers: {
          authorization: sessionStorage.getItem('authorization')
        },
        data: numArray
      });
         costData = res.data.Data;
           // 3. 遍历表单数据，匹配成本数据
  this.$refs.xGrid.getTableData()?.tableData.forEach(item => {
    // 根据OrgCode找到对应的成本项（若有多个匹配，取第一个）
    const matchedCost = costData.find(cost => cost.ItemCode === item.num);
    // 4. 反写cost列（未匹配到则设为0或空，根据需求调整）
    item.cost = matchedCost ? matchedCost.RmbPrice : '';
  });
   const totalCost = (this.$refs.xGrid.getTableData()?.tableData ?? []).reduce((sum, item) => sum + (item.cost ?? 0), 0);
   if (totalCost>0) {
       var insertData = []
          insertData.push({cost:totalCost})
       $table.insertAt(insertData, -1);
   }      
  }else if(param==='结构'){
 const res = await request({
        method: 'post',
  // url: ' /rest/v1/formFunction/obtainCostInformation?user='+sessionStorage.getItem('userID')+'&form=结构',
    url: ' /rest/v1/formFunction/obtainCostInformation?user='+sessionStorage.getItem('userID')+'&form=结构',

         headers: {
          authorization: sessionStorage.getItem('authorization'),
         'Content-Type': 'application/json'
        },
        data:  numArray
      });
         costData = res.data.Data;
           // 3. 遍历表单数据，匹配成本数据
  this.$refs.xGrid.getTableData()?.tableData.forEach(item => {
    // 根据OrgCode找到对应的成本项（若有多个匹配，取第一个）
    const matchedCost = costData.find(cost => cost.ItemCode === item.num);
    // 4. 反写cost列（未匹配到则设为0或空，根据需求调整）
    item.cost = matchedCost ? matchedCost.RmbPrice : '';
  });
  }


},
    handleOnMounted() {
      if (!!this.widget.options.onMounted) {
        let customFunc = new Function(this.widget.options.onMounted);
        customFunc.call(this);
      }
    },
    // 获取表单所有下拉组件的下拉选项
    async getSelectOptions() {
      const enumDefKeys = this.widget.options.tableColumns.reduce((pre, cur) => {
        if (cur.edit && cur.enum?.enumOid && !pre.includes(cur.enum.enumOid)) {
          pre.push(cur.enum.enumOid);
        }
        return pre;
      }, []);
      if (!enumDefKeys.length) return;
      const res = await request({
        method: 'post',
        url: '/rest/v1/enum/getEnumItemsMap',
        data: {
          enumDefKeys
        }
      });
      if (res?.data?.success) {
        const data = res.data.data;
        const enumObj = {};
        Object.keys(data).forEach((key) => {
          // modify by nieyz 2025/4/10 修复下拉组件的选项值
          enumObj[key] = Object.keys(data[key]).map((item) => ({ label: data[key][item], value: item }));
        });
        return enumObj;
      }
      return {};
    },
    /**
     * 获取编辑组件的显示值
     * @author nieyz
     * @Date 2025-6-20
     * @param component 组件
     * @param row 行数据
     * @param column 列对象
     * @param emumData 组件枚举对象
     * @param enumObj 所有枚举的数据集合
     */
    getDisplayText(component, row, column, emumData, enumObj) {
      const value = row[column.field];
      if (component === 'select') {
        const optionList = emumData?.enumOid ? enumObj[emumData.enumOid] : emumData?.list || [];
        return optionList.find((item) => item.value == value)?.label || (value ?? '');
      }
      return value;
    },
    // 组装表单列数据，主要是处理编辑态组件的渲染，此处编辑态组件渲染是采用渲染函数的方式（h函数）

    sumNum(list = [], field) {
      let count = 0;
      list.forEach((item) => {
        count += Number(item[field]);
      });
      return count;
    },
    footerMethod({ columns, data }) {
      const arr = columns.map((column, _columnIndex) => {
        if (_columnIndex === 0) {
          return '合计';
        }
        const item = this.widget.options.tableColumns.find((each) => each.field === column.field);
        if (item && item.sum) {
          return this.sumNum(data, column.field);
        }
        return null;
      });
      return [arr];
    },
    async copyRow(row) {
      const record = cloneDeep(row);
      const $table = this.$refs.xGrid;
      const { row: newRow } = await $table.insertAt(record, row);
      await $table.setEditCell(newRow);
    },
    getTableData() {
      console.log('data', this.$refs.xGrid.getTableData());
    },
    async insertEvent() {
      const $table = this.$refs.xGrid;
      if (!$table) return;
      // modify by nieyz 2025/1/22 配置高级查询来添加数据时出现新增弹窗，否则直接添加行数据
      if (['1', '2'].includes(this.widget.options.datasourceType)) return (this.showDialog = true);
      const record = {};
      $table.insertAt(record, -1); // 插入到最后
      // modify by nieyz 2024/10/22 修改表单赋值逻辑
      this.globalModel.formModel[this.widget.options.name] = $table.getTableData()?.tableData || [];
    },
    removeSelectRows() {
      const $table = this.$refs.xGrid;
      if ($table) {
        $table.removeCheckboxRow();
        // modify by nieyz 2024/10/22 修改表单赋值逻辑
        this.globalModel.formModel[this.widget.options.name] = $table.getTableData()?.tableData || [];
      }
    },
    exportData() {
      const $table = this.$refs.xGrid;
      if ($table) {
        $table.openExport({
          // 默认勾选源
          original: true
        });
      }
    },
    importData() {
      const $table = this.$refs.xGrid;
      if ($table) {
        $table.importData();
        // modify by nieyz 2024/10/22 修改表单赋值逻辑
        this.globalModel.formModel[this.widget.options.name] = $table.getTableData()?.tableData || [];
      }
    },
    refresh() {
      if (['1', '2'].includes(this.widget.options.datasourceType)) {
        this.refreshSelectedObject();
      } else {
        // modify by nieyz 2024/10/22 修改表单赋值逻辑
        this.$refs.xGrid.reloadData(this.globalModel.formModel[this.widget.options.name]);
      }
    },
    formatter(row, column, cellValue) {
      return cellValue;
    },
    handlePageSizeChange(pageSize) {
      //
    },
    handleCurrentPageChange(currentPage) {
      //
    },
    operateButtonsClick(buttonName, rowIndex, row) {
      const func = new Function('buttonName', 'rowIndex', 'row', this.widget.options.onOperationButtonClick);
      func(buttonName, rowIndex, row);
    },
    async refreshSelectedObject() {
      let objectSearchList = null;
      const $table = this.$refs.xGrid;
      if (!$table) return;
      const tableData = $table.getTableData()?.tableData || [];
      if (tableData.length) {
        const obj = {};
        tableData.forEach(({ oid, branchid, otype }) => {
          if (obj[otype]) {
            obj[otype].oidList.push(oid);
            obj[otype].branchidList.push(branchid);
          } else {
            obj[otype] = {
              typeInthid: otype,
              oidList: [oid],
              branchidList: [branchid]
            };
          }
        });
        objectSearchList = Object.values(obj).map((item) => {
          if (item.branchidList.some((branchid) => branchid)) {
            return { typeInthid: item.typeInthid, branchidList: item.branchidList.filter((branchid) => branchid) };
          }
          return { typeInthid: item.typeInthid, oidList: item.oidList.filter((oid) => oid) };
        });
      }
      if (!objectSearchList) return;
      const {
        isMultiple,
        datasourceType,
        objectSelectData: { customParams, columns, contextList, typeList, keyword, viewCondition, conditionGroups, conditionJoint }
      } = this.widget.options;
      let res = null;
      if (datasourceType === '2') {
        const formConfig = this.getFormConfig();
        if (!customParams?.refreshUrlKey || !formConfig?.dataSources?.find((item) => item.dataSourceId === customParams?.refreshUrlKey)) return;
        const dataSource = formConfig.dataSources.find((item) => item.dataSourceId === customParams?.refreshUrlKey);
        const VFR = getFormRenderRef();
        const config = buildRequestConfig(dataSource, formConfig.dataSources, VFR);
        const data = await request(config);
        let dhFn = new Function('result', 'isSandbox', 'DSV', 'VFR', dataSource.dataHandlerCode);
        res = dhFn.call(null, data, isSandbox, dataSource, VFR);
      } else {
        res = await request({
          method: 'POST',
          url: '/rest/v1/search/queryByConditionForPage',
          data: {
            columns,
            contextList,
            typeList,
            viewCondition,
            needCount: true,
            keyword,
            pageNum: 1,
            pageSize: 10000,
            conditionGroups,
            conditionJoint,
            ignoreWrk: true,
            objectSearchList
          }
        });
      }
      if (Array.isArray(res?.data?.data?.list)) {
        const data = res.data.data.list.map((row) => this.transRowToModel(row));
        // modify by nieyz 2024/10/22 修改表单赋值逻辑
        this.globalModel.formModel[this.widget.options.name] = data;
      }
    },
    /**
     * @description 从对象中取属性的值,区分IBA与普通属性
     * @author nieyz
     * @Date 2025-4-14
     * @param { object } row 对象数据
     * @param { string } propsKey 属性名称
     */
    getPropertyValue(row, propsKey) {
      // IBA属性从对象中取值
      if (propsKey.startsWith('iba_')) {
        const key = propsKey.split('iba_')[1];
        return row.ibaAttrMapForSearch ? row.ibaAttrMapForSearch[key] || '' : '';
      }
      // 有真值时取真值, 有额外值时取额外值
      return row[propsKey] ? row[propsKey] : row.extAttrMapForSearch ? row.extAttrMapForSearch[propsKey] || '' : '';
    },
    // 将对象选择绑定的映射关系解析成对应值
    transSpanToValue(htmlString, row) {
      const parser = new DOMParser();
      const doc = parser.parseFromString(htmlString, 'text/html');
      const spans = doc.querySelectorAll('span');
      spans.forEach((span) => {
        // 获取span的父节点
        const parent = span.parentNode;
        const propsKey = span.getAttribute('value');
        // modify by nieyz 2025/4/14 将span的内容添加到父节点中，并移除span标签, iba属性取值要特殊处理
        parent.replaceChild(document.createTextNode(`${this.getPropertyValue(row, propsKey) || ''}`), span);
      });
      return doc.body.innerText;
    },
    transRowToModel(row) {
      const obj = { oid: row.oid, branchid: row.branchid, otype: row.otype };
      this.widget.options.objectSelectData?.attrMap?.map(({ props, attr, widgetType }) => {
        obj[props] = this.transSpanToValue(attr, row);
      });
      return obj;
    },

    async confirmFunc(data = []) {
      // modify by nieyz 2025/8/2 丁龙豪修改导入时逻辑
      const $table = this.$refs.xGrid;
      if ($table && data?.length) {
        var insertData = data.map((row) => this.transRowToModel(row));
        console.log('=============');
        console.log(insertData);
        if (this.widget.options.label === 'beijingse' || this.widget.options.label === 'jiegoujian') {
          try {
            //  insertData[0].num = '104110336AB';
            const res = await request({
              method: 'get',
              url: '/rest/v1/formFunction/addFormDataSingle?itemCode=' + insertData[0].num,
              headers: {
                authorization: sessionStorage.getItem('authorization')
              }
            }).then((res) => {
              const data2 = res.data.data;
              insertData[0].type = data2.u9_item_sPECS;
              insertData[0].life = data2.lifecycleState;
              insertData[0].amount = data2.storeQty;
              console.log(insertData);
            });
          } catch (error) {
            console.log(error);
          }
          console.log('=============');
          $table.insertAt(insertData, -1);
        } else if (this.widget.options.label === 'head-table-ding') {
          try {
            //  insertData[0].num = '20135036100';
            const res = await request({
              method: 'get',
              url: '/rest/v1/formFunction/addFormDataMany?itemCode=' + insertData[0].num,
              headers: {
                authorization: sessionStorage.getItem('authorization')
              }
            }).then((res) => {
              const data2 = res.data.data;
              for (let index = 0; index < data2.length; index++) {
                const element = data2[index];
                insertData[0].num = element.objectNumber;
                insertData[0].name = element.name;
                insertData[0].type = element.u9_item_sPECS;
                insertData[0].life = element.lifecycleState; //生命周期
                insertData[0].stock = element.storeQty; //库存
                insertData[0].amount = element.u9_BOMComponent_UsageQty; //用量
                console.log(insertData);
                $table.insertAt(insertData, -1);
              }
            });
          } catch (error) {
            console.log(error);
          }
        }else{
            var insertData = data.map((row) => this.transRowToModel(row));
              console.log('=============');
          $table.insertAt(insertData, -1);
        }

        // modify by nieyz 2024/10/22 修改表单赋值逻辑
        // this.globalModel.formModel[this.widget.options.name] = $table.getTableData()?.tableData || [];
      }
    }
  }
};
</script>
